#include "QtPlayersSelector.h" 

QtPlayersSelector::QtPlayersSelector(QWidget *parent): QWidget(parent)
{
	ui.setupUi(this);
	
	QObject::connect(ui.spinBox, SIGNAL(valueChanged(int)), this,  SLOT(OnPlayerCountChanged(int)));
	QObject::connect(ui.buttonBox, SIGNAL(accepted()), this,  SLOT(OnConfirm()));
	QObject::connect(ui.buttonBox, SIGNAL(rejected()), this,  SLOT(OnCancel()));

}

QtPlayersSelector::~QtPlayersSelector()
{
}

void QtPlayersSelector::OnPlayerCountChanged(int playerCount)
{
	SetPlayerCount(playerCount);
}

void QtPlayersSelector::SetPlayerCount(unsigned int newPlayerCount)
{
	unsigned int playerCount = players.size();

	if (playerCount > newPlayerCount)
	{
		std::list<QtPlayerEditor*>::iterator it = players.begin();

		for(unsigned int i=0; i<playerCount; i++)
		{
			if (i >= newPlayerCount)
			{
				QtPlayerEditor* playerEditor = *it;

				delete playerEditor;

				it = players.erase(it);
			}
			else
			{
				++it;
			}
		}

		players.erase(it, players.end());
	}
	else if (playerCount < newPlayerCount)
	{
		unsigned int increasedCount = newPlayerCount - playerCount;

		for(unsigned int i=0; i<increasedCount; i++)
		{
			QtPlayerEditor *playerEditor = new QtPlayerEditor(this);
			playerEditor->SetId(playerCount+i+1);
			ui.vboxLayout1->addWidget(playerEditor);
			players.push_back(playerEditor);
		}
	}
}

void QtPlayersSelector::GetPlayers(unsigned int minPlayerCount, unsigned int maxPlayerCount)
{
	ui.spinBox->setMinimum(minPlayerCount);
	ui.spinBox->setMaximum(maxPlayerCount);
	ui.spinBox->setValue(minPlayerCount);
	SetPlayerCount(minPlayerCount);

	show();
}

void QtPlayersSelector::paintEvent(QPaintEvent *)
{
	QPainter painter(this);

	//painter.setBrush(Qt::red);
	//painter.drawRect(rect());
}

void QtPlayersSelector::OnConfirm()
{
	hide();
}

void QtPlayersSelector::OnCancel()
{
	hide();
}
